package com.example.messengerapp.viewmodel

import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.messengerapp.ui.ChatFragment
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import java.util.UUID

class ChatViewModel : ViewModel() {

    private val _messages = MutableLiveData<List<ChatFragment.Message>>()
    val messages: LiveData<List<ChatFragment.Message>> get() = _messages

    private val _imageUri = MutableLiveData<Uri?>()
    val imageUri: LiveData<Uri?> get() = _imageUri

    private val _message = MutableLiveData<String>()
    val message: LiveData<String> get() = _message

    fun addMessage(message: ChatFragment.Message) {
        val updatedMessages = _messages.value?.toMutableList() ?: mutableListOf()
        updatedMessages.add(message)
        _messages.value = updatedMessages
    }

    fun setMessage(text: String) {
        _message.value = text
    }

    fun setImageUri(uri: Uri?) {
        _imageUri.value = uri
    }

    fun sendMessage() {
        val messageText = _message.value?.trim()
        if (!messageText.isNullOrEmpty()) {
            val userId = FirebaseAuth.getInstance().currentUser?.uid
            userId?.let {
                val databaseReference = FirebaseDatabase.getInstance().getReference("chats").push()
                val messageData = ChatFragment.Message(UUID.randomUUID().toString(), it, messageText, null)
                databaseReference.setValue(messageData)
            }
        }
    }

    fun sendMessageWithImage(imageUrl: String) {
        val userId = FirebaseAuth.getInstance().currentUser?.uid
        userId?.let {
            val databaseReference = FirebaseDatabase.getInstance().getReference("chats").push()
            val messageData = ChatFragment.Message(UUID.randomUUID().toString(), it, null, imageUrl)
            databaseReference.setValue(messageData)
        }
    }

    fun uploadImageToFirebase() {
        val uri = _imageUri.value ?: return
        val storageReference = FirebaseStorage.getInstance().getReference("chat_images/${System.currentTimeMillis()}.jpg")
        storageReference.putFile(uri)
            .addOnSuccessListener {
                storageReference.downloadUrl.addOnSuccessListener { uri ->
                    sendMessageWithImage(uri.toString())
                }
            }
    }
}
